package metr;

import connect.DBUtil;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import java.util.Vector;

public class QueryFrame extends JFrame {
    private JTable queryTable;
    private DefaultTableModel tableModel;

    public QueryFrame() {
        setTitle("查询功能");
        setSize(800, 600);
        setLocationRelativeTo(null);

        JPanel panel = new JPanel(new BorderLayout());

        // 顶部查询条件区域
        JPanel conditionPanel = new JPanel(new GridLayout(2, 4, 10, 10));
        conditionPanel.setBorder(BorderFactory.createTitledBorder("查询条件"));

        JTextField nameField = new JTextField();
        JTextField supplierField = new JTextField();
        JTextField minStockField = new JTextField();
        JTextField maxStockField = new JTextField();

        conditionPanel.add(new JLabel("商品名称:"));
        conditionPanel.add(nameField);
        conditionPanel.add(new JLabel("供应商:"));
        conditionPanel.add(supplierField);
        conditionPanel.add(new JLabel("最小库存:"));
        conditionPanel.add(minStockField);
        conditionPanel.add(new JLabel("最大库存:"));
        conditionPanel.add(maxStockField);

        JButton queryBtn = new JButton("查询");
        JButton resetBtn = new JButton("重置");

        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
        buttonPanel.add(queryBtn);
        buttonPanel.add(resetBtn);

        JPanel topPanel = new JPanel(new BorderLayout());
        topPanel.add(conditionPanel, BorderLayout.CENTER);
        topPanel.add(buttonPanel, BorderLayout.SOUTH);

        panel.add(topPanel, BorderLayout.NORTH);

        // 中间表格区域
        tableModel = new DefaultTableModel();
        tableModel.addColumn("商品ID");
        tableModel.addColumn("商品名称");
        tableModel.addColumn("规格");
        tableModel.addColumn("单价");
        tableModel.addColumn("库存数量");
        tableModel.addColumn("供应商");
        tableModel.addColumn("最低库存");
        tableModel.addColumn("最高库存");

        queryTable = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(queryTable);
        panel.add(scrollPane, BorderLayout.CENTER);

        add(panel);

        // 加载所有商品数据
        loadAllProducts();

        // 按钮事件
        queryBtn.addActionListener(e -> {
            String name = nameField.getText().trim();
            String supplier = supplierField.getText().trim();
            String minStockStr = minStockField.getText().trim();
            String maxStockStr = maxStockField.getText().trim();

            try {
                int minStock = minStockStr.isEmpty() ? -1 : Integer.parseInt(minStockStr);
                int maxStock = maxStockStr.isEmpty() ? -1 : Integer.parseInt(maxStockStr);

                queryProducts(name, supplier, minStock, maxStock);
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(this, "请输入有效的数字", "错误", JOptionPane.ERROR_MESSAGE);
            }
        });

        resetBtn.addActionListener(e -> {
            nameField.setText("");
            supplierField.setText("");
            minStockField.setText("");
            maxStockField.setText("");
            loadAllProducts();
        });
    }

    private void loadAllProducts() {
        queryProducts("", "", -1, -1);
    }

    private void queryProducts(String name, String supplier, int minStock, int maxStock) {
        tableModel.setRowCount(0);

        StringBuilder sql = new StringBuilder("SELECT * FROM products WHERE 1=1");

        if (!name.isEmpty()) {
            sql.append(" AND name LIKE ?");
        }
        if (!supplier.isEmpty()) {
            sql.append(" AND supplier LIKE ?");
        }
        if (minStock >= 0) {
            sql.append(" AND stock_quantity >= ?");
        }
        if (maxStock >= 0) {
            sql.append(" AND stock_quantity <= ?");
        }

        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql.toString())) {

            int paramIndex = 1;

            if (!name.isEmpty()) {
                stmt.setString(paramIndex++, "%" + name + "%");
            }
            if (!supplier.isEmpty()) {
                stmt.setString(paramIndex++, "%" + supplier + "%");
            }
            if (minStock >= 0) {
                stmt.setInt(paramIndex++, minStock);
            }
            if (maxStock >= 0) {
                stmt.setInt(paramIndex++, maxStock);
            }

            ResultSet rs = stmt.executeQuery();

            while (rs.next()) {
                Vector<Object> row = new Vector<>();
                row.add(rs.getInt("product_id"));
                row.add(rs.getString("name"));
                row.add(rs.getString("specification"));
                row.add(rs.getDouble("price"));
                row.add(rs.getInt("stock_quantity"));
                row.add(rs.getString("supplier"));
                row.add(rs.getInt("min_stock"));
                row.add(rs.getInt("max_stock"));
                tableModel.addRow(row);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "查询商品失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
}